package cn.zn.menu.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.zn.base.common.constant.UserConstants;
import cn.zn.base.common.utils.AdminUtil;
import cn.zn.base.exception.CustomException;
import cn.zn.menu.dto.MetaDto;
import cn.zn.menu.dto.RouterDto;
import cn.zn.menu.dto.TreeSelectDto;
import cn.zn.menu.entity.SysMenu;
import cn.zn.role.entity.SysRoleMenu;
import cn.zn.user.entity.SysUser;
import cn.zn.menu.mapper.SysMenuMapper;
import cn.zn.role.mapper.SysRoleMenuMapper;
import cn.zn.menu.service.SysMenuService;
import cn.zn.menu.vo.SysMenuEditVo;
import cn.zn.menu.vo.SysMenuPageVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zn-admin
 * @since 2021-01-28
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

    @Autowired
    private SysRoleMenuMapper roleMenuMapper;

    @Override
    public Set<String> selectMenuPermsByUserId(String userId, String loginName) {
        Set<String> permsSet = new HashSet<>();
        // 管理员拥有所有权限
        if (AdminUtil.isAdmin(loginName)) {
            permsSet.add("*:*:*");
        } else {
            List<String> perms = baseMapper.selectMenuPermsByUserId(userId);
            for (String perm : perms) {
                if (StrUtil.isNotBlank(perm)) {
                    permsSet.addAll(Arrays.asList(perm.trim().split(",")));
                }
            }
        }
        return permsSet;
    }

    @Override
    public List<SysMenu> selectMenuTreeByUserId(String userId, String loginName, String[] systemNames) {
        List<SysMenu> menus = null;

        if (ArrayUtil.isNotEmpty(systemNames)) {
            systemNames = ArrayUtil.append(systemNames, "common");
        }

        if (AdminUtil.isAdmin(loginName)) {
            menus = baseMapper.selectMenuTreeAll(systemNames);
        } else {
            menus = baseMapper.selectMenuTreeByUserId(userId, systemNames);
        }
        return getMenuTree(menus);
    }

    @Override
    public List<SysMenu> selectMenuList(SysMenuPageVo vo, SysUser theUser) {
        if (ArrayUtil.isNotEmpty(vo.getSystemNames())) {
            vo.setSystemNames(ArrayUtil.append(vo.getSystemNames(), "common"));
        }
        return baseMapper.selectMenuList(vo);
    }

    /**
     * 根据父节点的ID获取所有子节点
     *
     * @param list 分类表
     * @return String
     */
    private List<SysMenu> getMenuTree(List<SysMenu> list) {
        List<SysMenu> returnList = new ArrayList<>();
        for (SysMenu sysMenu : list) {
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if ("0".equals(sysMenu.getParentId())) {
                recursionFn(list, sysMenu);
                returnList.add(sysMenu);
            }
        }
        return returnList;
    }

    /**
     * 递归列表
     *
     * @param list    菜单
     * @param sysMenu 上级菜单
     */
    private void recursionFn(List<SysMenu> list, SysMenu sysMenu) {
        // 得到子节点列表
        List<SysMenu> childList = getChildren(list, sysMenu);
        sysMenu.setChildren(childList);
        for (SysMenu tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysMenu> getChildren(List<SysMenu> list, SysMenu sysMenu) {
        List<SysMenu> children = new ArrayList<>();
        for (SysMenu n : list) {
            if (sysMenu.getId().equals(n.getParentId())) {
                children.add(n);
            }
        }
        return children;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysMenu> list, SysMenu sysMenu) {
        return getChildren(list, sysMenu).size() > 0;
    }

    @Override
    public List<RouterDto> buildMenus(List<SysMenu> menus) {
        List<RouterDto> routers = new LinkedList<>();
        for (SysMenu menu : menus) {
            RouterDto router = new RouterDto();

            if (UserConstants.YES_FRAME.equals(menu.getIsFrame())) {
                router.setPath(menu.getPath());
                router.setName(menu.getPath());
                router.setComponent(menu.getComponent());
            } else {
                router.setHidden("1".equals(menu.getVisible()));
                router.setName(StrUtil.upperFirst(menu.getPath()));
                router.setPath(getRouterPath(menu));
                router.setComponent(getComponent(menu));
            }
            router.setMeta(new MetaDto(menu.getMenuName(), menu.getIcon(), StrUtil.equals("1", menu.getIsCache())));
            List<SysMenu> cMenus = menu.getChildren();
            if (CollUtil.isNotEmpty(cMenus) && UserConstants.TYPE_DIR.equals(menu.getMenuType())) {
                router.setAlwaysShow(true);
                router.setRedirect("noRedirect");
                router.setChildren(buildMenus(cMenus));
            }
            routers.add(router);
        }
        return routers;
    }

    @Override
    public List<TreeSelectDto> buildMenuTreeSelect(List<SysMenu> menus) {
        List<SysMenu> menuTrees = buildMenuTree(menus);
        return menuTrees.stream().map(TreeSelectDto::new).collect(Collectors.toList());
    }

    @Override
    public void insertMenu(SysMenuEditVo vo) {
        SysMenu menu = new SysMenu();
        BeanUtil.copyProperties(vo, menu);

        if (!"0".equals(menu.getParentId())) {
            SysMenu menuParent = baseMapper.selectById(menu.getParentId());
            menu.setSystemName(menuParent.getSystemName());
        }

        menu.insert();
    }

    @Override
    public void updateMenu(String id, SysMenuEditVo vo) {
        SysMenu menu = new SysMenu();
        BeanUtil.copyProperties(vo, menu);

        if (!"0".equals(menu.getParentId())) {
            SysMenu menuParent = baseMapper.selectById(menu.getParentId());
            menu.setSystemName(menuParent.getSystemName());
        }

        menu.setId(id);
        menu.updateById();
    }

    @Override
    public void deleteMenuById(String menuId) {
        QueryWrapper<SysMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", menuId);
        int count = baseMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new CustomException("存在子菜单,不允许删除");
        }

        QueryWrapper<SysRoleMenu> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("menu_id", menuId);
        count = roleMenuMapper.selectCount(queryWrapper1);
        if (count > 0) {
            throw new CustomException("菜单已分配,不允许删除");
        }

        baseMapper.deleteById(menuId);
    }

    /**
     * 获取路由名称
     *
     * @param menu 菜单信息
     * @return 路由名称
     */
    private String getRouteName(SysMenu menu) {
        String routerName = StrUtil.upperFirst(menu.getPath());
        // 非外链并且是一级目录（类型为目录）
        if (isMenuFrame(menu)) {
            routerName = StrUtil.EMPTY;
        }
        return routerName;
    }

    /**
     * 获取路由地址
     *
     * @param menu 菜单信息
     * @return 路由地址
     */
    private String getRouterPath(SysMenu menu) {
        String routerPath = menu.getPath();
        // 非外链并且是一级目录（类型为目录）
        if ("0".equals(menu.getParentId())) {
            if (UserConstants.TYPE_DIR.equals(menu.getMenuType()) && UserConstants.NO_FRAME.equals(menu.getIsFrame())) {
                routerPath = "/" + menu.getPath();
            }
        }
        return routerPath;
    }

    /**
     * 获取组件信息
     *
     * @param menu 菜单信息
     * @return 组件信息
     */
    private String getComponent(SysMenu menu) {
        String component = UserConstants.LAYOUT;
        if (StrUtil.isNotBlank(menu.getComponent())) {
            if (UserConstants.NO_FRAME.equals(menu.getIsFrame())) {
                component = menu.getComponent();
            }
        } else {
            if (isParentView(menu)) {
                component = UserConstants.PARENT_VIEW;
            }
        }
        return component;
    }

    /**
     * 是否为菜单内部跳转
     *
     * @param menu 菜单信息
     * @return 结果
     */
    private boolean isMenuFrame(SysMenu menu) {
        return UserConstants.TYPE_MENU.equals(menu.getMenuType()) && UserConstants.NO_FRAME.equals(menu.getIsFrame());
    }

    /**
     * 是否为parent_view组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    private boolean isParentView(SysMenu menu) {
        return !"0".equals(menu.getParentId()) && UserConstants.TYPE_DIR.equals(menu.getMenuType());
    }

    /**
     * 构建前端所需要树结构
     *
     * @param menus 菜单列表
     * @return 树结构列表
     */
    private List<SysMenu> buildMenuTree(List<SysMenu> menus) {
        List<SysMenu> returnList = new ArrayList<>();
        List<String> tempList = new ArrayList<>();
        for (SysMenu dept : menus) {
            tempList.add(dept.getId());
        }
        for (SysMenu menu : menus) {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(menu.getParentId())) {
                recursionFn(menus, menu);
                returnList.add(menu);
            }
        }
        if (returnList.isEmpty()) {
            returnList = menus;
        }
        return returnList;
    }

}
